package service

import (
	"apitestAfterGo/dao"
	"apitestAfterGo/domain"
	"apitestAfterGo/dto"
	"github.com/zhuxiujia/GoMybatis"
)

type systemService struct {
	systemMapper       *domain.SystemMapper
	GetSystems         func(dto dto.SystemByPageInputDto) ([]domain.System, error) `tx:"" rollback:"error"`
	GetAllSystemCount  func(dto dto.SystemByPageInputDto) (int, error)             `tx:"" rollback:"error"`
	GetSystemsByPage   func(dto dto.SystemByPageInputDto) ([]domain.System, error) `tx:"" rollback:"error"`
	DeleteSystemById   func(id int) (int64, error)                                 `tx:"" rollback:"error"`
	AddSystem          func(dto dto.SystemInputDto) (int64, error)                 `tx:"" rollback:"error"`
	ModifySystemById   func(dto dto.SystemInputDto) (int64, error)                 `tx:"" rollback:"error"`
	GetUsersBySystemId func(id int) ([]int, error)                                 `tx:"" rollback:"error"`
	GetSystemById      func(id int) (domain.System, error)                         `tx:"" rollback:"error"`
	AddUsersBySystemId func(dto dto.GrantSystemInputDto) (int64, error)            `tx:"" rollback:"error"`
}

var SystemServiceImpl systemService

func init() {
	SystemServiceImpl = systemService{
		systemMapper: &dao.SystemMapper,
		GetSystems: func(dto dto.SystemByPageInputDto) ([]domain.System, error) {
			dto.Current = (dto.Current - 1) * dto.PageSize
			return SystemServiceImpl.systemMapper.SelectSystemsByUserId(dto)
		},
		GetAllSystemCount: func(dto dto.SystemByPageInputDto) (int, error) {
			return SystemServiceImpl.systemMapper.GetAllSystemCount(dto)
		},
		GetSystemsByPage: func(dto dto.SystemByPageInputDto) ([]domain.System, error) {
			dto.Current = (dto.Current - 1) * dto.PageSize
			return SystemServiceImpl.systemMapper.GetSystemsByPage(dto)
		},
		DeleteSystemById: func(id int) (int64, error) {
			return SystemServiceImpl.systemMapper.DeleteTemplate(id)
		},
		AddSystem: func(dto dto.SystemInputDto) (int64, error) {
			return SystemServiceImpl.systemMapper.AddSystem(dto)
		},
		ModifySystemById: func(dto dto.SystemInputDto) (int64, error) {
			return SystemServiceImpl.systemMapper.ModifySystemById(dto)
		},
		GetUsersBySystemId: func(id int) ([]int, error) {
			users, _ := SystemServiceImpl.systemMapper.GetUsersBySystemId(id)
			userIds := make([]int, len(users))
			for i := range users {
				userIds[i] = users[i].Id
			}
			return userIds, nil
		},
		GetSystemById: func(id int) (domain.System, error) {
			return SystemServiceImpl.systemMapper.SelectTemplate(id)
		},
		AddUsersBySystemId: func(dto dto.GrantSystemInputDto) (int64, error) {
			SystemServiceImpl.systemMapper.DeleteUsersById(dto.Id)
			for i := range dto.Ids {
				SystemServiceImpl.systemMapper.AddUsersBySystemId(dto.Id, dto.Ids[i])
			}
			return 1, nil
		},
	}
	GoMybatis.AopProxyService(&SystemServiceImpl, &dao.Engine)
}
